<template>
  <div>
    <el-form :inline="true" :model="form" class="custom-left-form">
      <el-form-item class="custom-label-item">
        <template slot="label">
          <span style="font-size: 20px;">医院机构</span>
        </template>
        <el-select v-model="queryParams.ID_ORG" placeholder="请选择机构" style="width: 200px">
          <el-option v-for="item in provinceOptions" :key="item.ID_ORG" :label="item.NA" :value="item.ID_ORG"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.numberVis" placeholder="请输入就诊号码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="queryVisInfoById()">就诊结算查询</el-button>
        <el-button type="success" @click="pushMedica()">上传医保</el-button>
      </el-form-item>
    </el-form>

    <!-- 1. 新增表格勾选列 + 绑定选中数据 -->
    <el-table
        :data="tableData"
        style="width: 100%"
        :fit="true"
        border
        class="thick-black-border"
        ref="multipleTable"
    @selection-change="handleSelectionChange"
    >
    <!-- 新增：勾选列 -->
    <el-table-column type="selection" width="55"></el-table-column>

    <el-table-column prop="ORGNAME" label="机构" min-width="75"></el-table-column>
    <el-table-column prop="NA_PI" label="姓名" min-width="50"></el-table-column>
    <el-table-column prop="NUM_VISMED" label="就诊号码" min-width="75"></el-table-column>
    <el-table-column prop="CD_DIE_MAJ" label="主诊断编码" min-width="65"></el-table-column>
    <el-table-column prop="NA_DIE_MAJ" label="主诊断名称" min-width="65"></el-table-column>
    <el-table-column prop="INSUPLC_ADMDVS" label="参保地行政区划" min-width="75"></el-table-column>
    <el-table-column prop="MDTRTAREA_ADMVS" label="就医地行政区划" min-width="75"></el-table-column>
    <el-table-column prop="CD_PIRECI" label="发票号码"></el-table-column>
    <el-table-column prop="DZPJHM" label="电子票据号码"></el-table-column>
    <el-table-column prop="DZPJDM" label="电子票据代码"></el-table-column>
    <el-table-column prop="DZJYM" label="电子校验码"></el-table-column>
    <el-table-column prop="SCRQ" label="开票日期"></el-table-column>
    <el-table-column prop="AMT_PIRECIS" label="发票金额"></el-table-column>
    <el-table-column prop="DZPJWWYM" label="电子票据页面(点击地址打开)" class-name="nowrap-column" min-width="200">
      <template slot-scope="scope">
        <el-tooltip class="item" effect="dark" :content="scope.row.DZPJWWYM" placement="top">
          <a :href="scope.row.DZPJWWYM" target="_blank" class="safe-link" style="font-size: 18px;color: crimson">
            <span class="ellipsis-text">{{ scope.row.DZPJWWYM }}</span>
          </a>
        </el-tooltip>
      </template>
    </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {queryVisInfoById, uplodMedica} from "@/views/ybydbx/ybydbx";

export default {
  name: 'electronic-bill-upload',
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 86400000;
        }
      },
      queryParams: {
        ID_ORG: '68400db9caaa060001b96f85',
        date: [],
        numberVis: ''
      },
      provinceOptions: [{
        ID_ORG: '68400db9caaa060001b96f85',
        NA: '平昌县人民医院'
      }, {
        ID_ORG: '68401005caaa060001b96f9f',
        NA: '平昌县中医医院'
      }],
      form: {},
      tableData: [],
      // 2. 新增：存储选中的表格数据
      selectedRows: []
    }
  },
  mounted() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth();
    const firstDay = new Date(currentYear, currentMonth, 1);
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    this.queryParams.date = [firstDay, lastDay];
  },
  methods: {
    // 3. 新增：处理表格选中事件，更新选中数据
    handleSelectionChange(val) {
      this.selectedRows = val;
      console.log('选中的数据：', this.selectedRows);
    },

    async queryVisInfoById() {
      debugger
      console.log('查询就诊记录参数:', this.queryParams);
      let params = {
        idOrg: this.queryParams.ID_ORG,
        numberVis: this.queryParams.numberVis
      }
      try {
        const res = await queryVisInfoById(params)
        if (res && res.code !== '200') {
          console.log("获取就诊结算信息失败:", res.msg)
          this.$message.error("获取就诊结算信息失败:" + res.msg)
          return false
        }
        this.tableData = res.data || []
        // 查询后清空选中状态（可选，根据业务需求）
        this.$refs.multipleTable?.clearSelection();
      } catch (error) {
        console.error('查询中心账单信息失败:', error)
      }
    },

    async pushMedica() {
      debugger
      // 4. 新增：校验是否选中数据
      if (this.selectedRows.length === 0 || this.selectedRows.length >100) {
        this.$message.warning('请先勾选需要上传的医保数据,或者勾选数据超过100！');
        return;
      }


      // 5. 组装参数：invoiceList 替换为选中的数据
      let params = {
        idOrg: this.queryParams.ID_ORG,
        invoiceList: this.selectedRows  // 核心修改：仅传选中的数据
      }
      try {
        const res = await uplodMedica(params);
        console.log("医保上传结果:", res);

        if (res && res.code === '200') {
          this.$message.success('数据上传医保成功');
          // 上传成功后清空选中状态（可选）
          this.$refs.multipleTable?.clearSelection();
        } else {
          this.$message.error(`上传失败：${res?.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('医保上传接口调用失败:', error);
        this.$message.error('上传过程发生异常，请稍后重试');
      }
    }
  }
}
</script>

<style scoped>
/* 原有样式完全保留，无需修改 */
::v-deep .thick-black-border .el-table__header th .cell {
  text-align: center !important;
}

::v-deep .thick-black-border .el-table__header th {
  color: #000 !important;
}

::v-deep .thick-black-border .el-table__body td {
  color: #000 !important;
}

::v-deep .thick-black-border .el-table__body td.nowrap-column {
  color: inherit !important;
}

::v-deep .thick-black-border {
  border: 2px solid #000 !important;
}

::v-deep .thick-black-border th {
  border-right: 2px solid #000 !important;
  border-bottom: 2px solid #000 !important;
}

::v-deep .thick-black-border td {
  border-right: 2px solid #000 !important;
  border-bottom: 2px solid #000 !important;
}

::v-deep .thick-black-border th:last-child,
::v-deep .thick-black-border td:last-child {
  border-right: none !important;
}

::v-deep .thick-black-border .el-table__row:hover td {
  border-right: 2px solid #000 !important;
  border-bottom: 2px solid #000 !important;
}

.ellipsis-text {
  display: inline-block;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nowrap-column .cell {
  padding: 0 10px;
}
</style>